package cn.dlc.com.order.controller;

import cn.dlc.com.order.entity.Product;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author 邓立川
 * @date 2020/12/31 17:40
 * @desc 添加当前类的描述信息
 */
@RestController
@RequestMapping("order")
@Slf4j
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    // blockHandler：指定降级
//    @SentinelResource(value="findById",blockHandler = "orderBlockHandler",fallback = "orderFallBack")
    @SentinelResource(value="findById",blockHandler = "orderBlockHandler",
            fallbackClass = FallBackClass.class,fallback = "orderFallBack")
    @GetMapping("{id}")
    public Product findById(@PathVariable("id") String id) {
        // 替换为服务名product-server
        System.out.println("id" + id);
        Product product = restTemplate.getForObject("http://product-server/product/" + id, Product.class);
        return product;
    }

    // 要配置控制台的降级规则
    public Product orderFallBack(String id, Throwable throwable){
        Product product = new Product();
        product.setDesc("出现未知异常调用的方法1");
        return product;
    }

    // 要配置控制台的流控规则，没有配置这个进入异常的降级方法
    public Product orderBlockHandler(String id, BlockException ex) {
        Product product = new Product();
        product.setDesc("访问被限流或服务降级调用的方法");
        return product;
    }
}
